using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;  

public partial class UserWizard : System.Web.UI.Page
{
    HDDatabase HDD;
    HtmlForm frmObj;
    DynamicDisplayI DDI;

    DataSet dsePageInfo = new DataSet();
    DataTable dtaData = new DataTable();
    DataSet dseInputInfo;
    DataSet dseTempInputInfo = new DataSet();

    string strErrMessage = "";
    int intRowCnt = 1;
    int intDelCnt = 0;

    bool IsEdit = false;
    bool IsCopy = false;
    string strPageKey = "";

    string strUserID = "";
    string strUserAFID = "";
    string strUserName = "";
    DataRow drpage = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Session["dseTempInputInfo"] != null)
        //    if (!IsPostBack)
        //        Response.Redirect(Request.UrlReferrer.ToString());

        security hdds = new security();

        if (Session["userid"] == null)
            Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "")
            Response.Redirect(hdds.SessionExpiryURL);


        //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["mn"] != null)
        {
            if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
            {
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                User_Wizard.Visible = false;
                return;
            }
        }

        //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        {
            if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
            {
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                User_Wizard.Visible = false;
                return;
            }
        }

        HDD = new HDDatabase();
        User_Wizard.DisplaySideBar = false;

        if (this.Master.FindControl("Form1") != null)
        {
            frmObj = (HtmlForm)this.Master.FindControl("Form1");
        }

        if (Page.IsPostBack == false)
        {
            LoadParentDD();
            LoadReportingTo();
            loadLocales();
            GlobalValues.loadwizard = false;
            GlobalValues.loadeventwizard = false;
            loadOwneridDropDown();
            LoadDashboards();
        }
        //PageCommonFunctions PCF = new PageCommonFunctions();
        //PCF.AddSearchLink(ref tdownerid, "owner_id", "User_Wizard_ownerid", "User_Wizard_txt_ownerid", "92");
        CheckForChangeOwner();
        string strPK = "";
        if (Request.QueryString["PK"] != null)
        {
            strPK = Request.QueryString["PK"].ToString();
        }

        imgsearch.Attributes.Add("onclick", "javascript:openlookupwindow('User_Wizard_ownerid','User_Wizard_txt_ownerid','f496930dfe0b690f','" + strPK + "','" + HttpContext.Current.Request.QueryString["pgs_id"].ToString() + "');");

        ScreenReader SR = new ScreenReader();
        this.LoadTreeView(); // Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security
        if (Request.QueryString["PK"] != null)
        {
            IsEdit = true;
            strPageKey = HDD.GetColumnValue("sy_usr", "user_id", "af_row_id = '" + Request.QueryString["PK"].ToString() + "'");
            ps_rowkey.Value = HDD.GetColumnValue("sy_usr", "af_row_id", "user_id = '" + strPageKey.Replace("'", "''") + "'");
            HF_password.Value = HDD.GetColumnValue("sy_usr", "password", "user_id = '" + strPageKey.Replace("'", "''") + "'");
            lbl_password.Visible = false;
            TB_password.Visible = false;
            RequiredFieldValidator4.Display = ValidatorDisplay.None;
            RequiredFieldValidator4.Enabled = false;
            img_pass.Visible = false;
            //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
            if (!IsPostBack)
            {
                HF_user_business_rowkey.Value = HDD.GetColumnValue("sy_usr", "af_row_id", "user_id = '" + ps_rowkey.Value + "'");
                this.LoadValuesOnEdit();
            }
            //----------------End for Org Security------------------
            if (Page.IsPostBack == false)
            {
                LoadWizardUserEdit();
            }
            User_Wizard.HeaderText = "Users - Edit";
            lblHeader.Text = "Users - Edit";
            
        }
        else
        {
            ps_rowkey.Value = SR.getHashKey();
            HF_user_role_rowkey.Value = SR.getHashKey();

            if (!Page.IsPostBack)
            {
                CB_Active.Checked = true;
            }
        }

        if (Request.QueryString["CPY"] != null)
        {
            User_Wizard.HeaderText = "Users - Copy";
            lblHeader.Text = "Users - Copy";
            IsCopy = true;
            strPageKey = HDD.GetColumnValue("sy_usr", "user_id", "af_row_id = '" + Request.QueryString["PK"].ToString() + "'");
            ps_rowkey.Value = SR.getHashKey();
            HF_user_role_rowkey.Value = SR.getHashKey();
            lbl_password.Visible = true;
            TB_password.Visible = true;
            img_pass.Visible = true;
            CB_Active.Checked = true;
        }
        drpage = GetPageDataRow();
        isViewMode();
        showResetPassword();
        setHeaderText();
        if (!Page.IsPostBack)
        {
            getpageicons();
        }
        //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
        //if (hih_SelectedTreeNode.Value != "")
        //{
        LoadValuesOnPostBack();
        //}
        //----------------End for Org Security------------------
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
        {
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                //replaceInputControlsWithLabels(this.frmObj);
            }
        }

        //Code added by Sampath on 26-Nov-2012 for Change admin name implementation
        //disable controls for Admin user based on the configuration settings in Edit Mode
        if (IsEdit)
        {
            if (Request.QueryString["CPY"] == null)
            {
                if (Session["user_afrowid"].ToString() == "650a333596bbf348" && Request.QueryString["PK"] == "650a333596bbf348") //admin
                {
                    disableControlsforAdmin();
                }
            }
        }

        //code added by Sampath for IPP on 14-Oct-2011
        if (Session["client_application"] != null)
        {
            if (Session["client_application"].ToString().ToLower() == "ipp")
            {
                disableControls();
            }
        }
    }

    private void disableControlsforAdmin()
    {
        HDD = new HDDatabase();
        try
        {
            DataTable dt = HDD.GetDataTable("select mem_id, mem_value1 from sy_acr_mem where acr_id='6b9bb62d272105f1' and mem_value1='false' order by mem_seq");
            if (dt != null)
            {
                if (dt.Rows.Count == 0) return;
                foreach (DataRow dr in dt.Rows)
                {
                    switch (dr["mem_id"].ToString().ToLower())
                    { 
                        case "user_id":
                            TB_user_id.Enabled = false;
                            break;
                        case "title":
                            DD_title.Enabled = false;
                            break;
                        case "reporting_to":
                            DD_reporting_to.Enabled = false;
                            break;
                        case "custodian_filter":
                            DD_custodian_filter.Enabled = false;
                            break;
                        case "active":
                            CB_Active.Enabled = false;
                            break;
                        case "role_id":
                            DD_role_id.Enabled = false;
                            break;
                        case "owner_id":
                            imgsearch.Visible = false;
                            txt_ownerid.Enabled = false;
                            break;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("disableControlsforAdmin: Error:  " + ex.Message);
        }
        finally
        {
            //HDD = null;
        }
    }

    private void disableControls()
    {
        try
        {
            TB_first_name.Enabled = false;
            TB_last_name.Enabled = false;
            TB_mid_initial.Enabled = false;
            TB_user_id.Enabled = false;
            TB_password.Enabled = false;
            DD_title.Enabled = false;
            DD_role_id.Enabled = false;
            DD_custodian_filter.Enabled = false;
            DD_hint_question.Enabled = false;
            TB_hint_answer.Enabled = false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("disableControls: Error:  " + ex.Message);
        }
    }

    private void replaceInputControlsWithLabels(HtmlForm frm)
    {
        ArrayList alControls = new ArrayList();
        _replaceInputControl(this,ref alControls);
        for (int i = 0; i < alControls.Count; i++)
        {
            Control cc = (Control)alControls[i];
            if (cc is TextBox)
            {
                TextBox tb = (TextBox)cc;                  
                cc.Parent.Controls.Add(getLabel(tb.Text,tb.ID));
                tb.Visible = false;
                //alControls.Add(tb);
            }
            if (cc is DropDownList)
            {
                DropDownList tb = (DropDownList)cc;
                string str = "";
                if (tb.Items.Count > 0)
                {
                    if (tb.SelectedIndex > -1)
                        str = tb.Items[tb.SelectedIndex].Text;
                    else
                        str = tb.Items[0].Text;
                }
                cc.Parent.Controls.Add(getLabel(str, tb.ID));
                tb.Visible = false;
                //alControls.Add(tb);
            }
            if (cc is Button)
            {
                Button tb = (Button)cc;
                tb.Visible = false;
                //disableControls(cc);
            }
            if (cc is HtmlInputButton)
            {
                HtmlInputButton tb = (HtmlInputButton)cc;
                tb.Visible = false;
                //disableControls(cc);
            }
            if (cc is CheckBox)
            {
                CheckBox tb = (CheckBox)cc;
                cc.Parent.Controls.Add(getLabel(tb.Checked == true ? "true" : "false", tb.ID));
                tb.Visible = false;
                //alControls.Add(tb);
            }
            if (cc is HtmlImage)
            {
                //HtmlImage tb = (HtmlImage)cc;
                //tb.Style.Add("display", "none");
            }
            if (cc is HtmlInputImage)
            {
                //HtmlInputImage tb = (HtmlInputImage)cc;
                //tb.Style.Add("display", "none");
            }
            if (cc is Image)
            {
                //Image tb = (Image)cc;
                //tb.Style.Add("disabled", "true");
            }
            if (cc is FileUpload)
            {
                FileUpload tb = (FileUpload)cc;
                tb.Enabled = false;
            }
            if (cc is ListBox)
            {
                ListBox lb = (ListBox)cc;
                lb.Enabled = false;
            }
        }
        //try
        //{
        //    //foreach (Control cc in frm.Controls)
        //        _replaceInputControl(this);
        //}
        //catch (Exception ee)
        //{

        //}
    }
    //private void _replaceInputControls(Control cc)
    //{
    //    bool hasChild = false;
    //    //for (int i = 0; i < cc.Count; i++)
    //    {
    //        hasChild = false;
    //        if (cc.Controls != null)
    //        {
    //            if (cc.Controls.Count > 0)
    //            {
    //                hasChild = true;
    //                _replaceInputControls(cc.Controls);
    //            }
    //        }
    //        if (!hasChild)
    //            _replaceInputControl(cc[i]);
    //    }
    //}
    private Label getLabel(string text, string id)
    {
        Label l1 = new Label();
        l1.ID = "lbl_view_mode_" + id;
        l1.Text = text;        
        return l1;
    }
    private void _replaceInputControl(Control cc1,ref ArrayList alControls)
    {
        foreach (Control cc in cc1.Controls)
        {
            //if (cc.ID!=null)
            //    if (cc.ID.ToLower().IndexOf("btnsave") > -1)
            //        temp = cc.ID;
            if (cc is TextBox)
            {
                TextBox tb = (TextBox)cc;
                //cc.Parent.Controls.Add(getLabel(tb.Text,tb.ID));
                //tb.Visible = false;
                alControls.Add(tb);
            }
            if (cc is DropDownList)
            {
                DropDownList tb = (DropDownList)cc;
                //cc.Parent.Controls.Add(getLabel(tb.Text, tb.ID));
                //tb.Visible = false;
                alControls.Add(tb);
            }
            if (cc is Button)
            {
                Button tb = (Button)cc;
                tb.Visible = false;
                //disableControls(cc);
            }
            if (cc is HtmlInputButton)
            {
                HtmlInputButton tb = (HtmlInputButton)cc;
                tb.Visible = false;
                //disableControls(cc);
            }
            if (cc is CheckBox)
            {
                CheckBox tb = (CheckBox)cc;
                //cc.Parent.Controls.Add(getLabel(tb.Checked == true ? "true" : "false", tb.ID));
                //tb.Visible = false;
                alControls.Add(tb);
            }
            if (cc is HtmlImage)
            {
                //HtmlImage tb = (HtmlImage)cc;
                //tb.Style.Add("display", "none");
            }
            if (cc is HtmlInputImage)
            {
                //HtmlInputImage tb = (HtmlInputImage)cc;
                //tb.Style.Add("display", "none");
            }
            if (cc is Image)
            {
                //Image tb = (Image)cc;
                //tb.Style.Add("disabled", "true");
            }
            if (cc is FileUpload)
            {
                FileUpload tb = (FileUpload)cc;
                tb.Enabled = false;
            }
            if (cc is ListBox)
            {
                ListBox lb = (ListBox)cc;
                lb.Enabled = false;
            }
            //disableControls(cc);
            _replaceInputControl(cc,ref alControls);
        }
    }
    private bool showResetPasswordFlag()
    {
        bool ret = false;
        bool addMode = Request.QueryString["CPY"] == null && Request.QueryString["PK"] == null;
        if (!addMode)
        {
            if (HttpContext.Current.Request.QueryString["VMODE"] == null)
            {
                if (Request.QueryString["CPY"] == null)
                {
                    if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
                        ret = true;
                    else if (Session["user_afrowid"].ToString() == "650a333596bbf348")
                    {
                        ret = Request.QueryString["PK"].ToString() != "650a333596bbf348" && Request.QueryString["PK"].ToString() != "e51e0327224a2eb9";
                    }
                    else if (Request.QueryString["PK"].ToString() != Session["user_afrowid"].ToString())
                        ret = true;
                    else if (Request.QueryString["PK"].ToString() == "650a333596bbf348")
                        ret = true;
                }
            }
        }
        return ret;
    }
    private void showResetPassword()
    {
        try
        {
            //enableButtonInCopyMode();
            DynamicDisplayI ddi = new DynamicDisplayI(); //Panel pnlTemp;
            Control ccTrigger = null;
            Control ccContent = null;
            //Control cc = ddi.FindControl(this.Controls, "btnResetPassword");          
            ccTrigger = ddi.FindControl(this.Controls, "resetPassworddivtrigger");
            if (ccTrigger == null)
                if (ccTrigger is Panel)
                {
                    ccTrigger.Visible = false;
                }
            ccContent = ddi.FindControl(this.Controls, "div_reset_password");
            if (ccContent == null)
                if (ccContent is Panel)
                {
                    ccContent.Visible = false;
                }
            ddi = null;
            if (ccContent == null || ccTrigger == null)
                return;
            if (IsPostBack)
                return;
            bool setThis = showResetPasswordFlag();
            //if (showResetPasswordFlag())
            {
                //btnResetPassword.Visible = false;        
                HDDatabase hdd = new HDDatabase();
                DataTable dt = hdd.GetDataTable("select * from sy_acr_mem where af_row_id='9e89a0a2844689f6'");
                hdd = null;
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["mem_value1"].ToString() == "true" || dt.Rows[0]["mem_value1"].ToString() == "1")
                        {

                            ccTrigger.Visible = setThis;
                            ccContent.Visible = setThis;
                            if (ccContent == null)
                                if (ccContent is Panel)
                                {
                                    Panel pp = (Panel)ccContent;
                                    pp.Style.Add("display", "none");//to avoid flickering
                                }
                        }
                        else
                        {
                            ccTrigger.Visible = false;
                            ccContent.Visible = false;
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in showFeedBackOption. " + e.Message);
        }
    }
    private void loadLocales()
    {
        DataTable dt = new DataTable();
        HDDatabase hdd = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
        DD_Locale.Items.Clear();
        try
        {

            dt = hdd.GetDataTable("Select locale_id,locale_name,is_default from sy_locales where is_neutral=0");
            DD_Locale.DataSource = dt;
            DD_Locale.DataTextField = "locale_name";
            DD_Locale.DataValueField = "locale_id";
            DD_Locale.DataBind();
            DataRow[] dr = dt.Select("is_default = 'true'");
            if(dr.Length>0)
                DD_Locale.Items.FindByValue(dr[0]["locale_id"].ToString()).Selected = true;
            #region Old code commented by 'Imran Gani' on 28-Feb-2014, for simple code
            //string temp = "";
            //if (dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        if (dr["is_default"].ToString().ToLower() == "true")
            //            temp = dr["locale_id"].ToString();
            //        DD_Locale.Items.Add(new ListItem(dr["locale_name"].ToString(), dr["locale_id"].ToString()));
            //    }
            //}
            //if (temp.Length > 0)
            //{
            //    DD_Locale.Items.FindByValue(temp).Selected = true;
            //}
            #endregion
            dt = HDD.GetDataTable("select * from sy_acr_mem where acr_id = '64650c9a6a126692';");
            if (dt.Rows.Count > 0)
            {
                dr = dt.Select("mem_id = 'locale'");
                if (dr.Length > 0)
                    DD_Locale.Items.FindByValue(dr[0]["mem_value1"].ToString()).Selected = true;
            }
        }
        catch (Exception e)
        {
            //            lbl_message.Text = e.Message;
            LogWriter.WriteLog("Error in loadLocales. " + e.Message);
        }
        finally
        {
            hdd = null;
            dt = null;
        }
    }
    private void isViewMode()
    {
        if (HttpContext.Current.Request.QueryString["VMODE"] != null)
            if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                Wizard wz = (Wizard)frmObj.FindControl("ContentPlaceHolder3").FindControl("User_Wizard");
                ddi.disableControls(wz);
                ddi = null;
                User_Wizard.HeaderText = "Users - View";//added by Prithi on Aug-04-2008
                imgsearch.Visible = false;
            }
    }
    public void LoadParentDD()
    {
        DataTable dt_defaultvalues = new DataTable(); // Added by 'Imran Gani' on 28-Feb-2014, for user default values
        dt_defaultvalues = HDD.GetDataTable("select * from sy_acr_mem where acr_id = '64650c9a6a126692';");
            
        string strSql;
        strSql = "select p_obj.timezone_id as [TimeID], p_obj.name as [TimeName]" +
                            " from sy_timezone p_obj where 1=1 order by TimeName";

        DD_time_zone.DataSource = HDD.GetDataTable(strSql);
        DD_time_zone.DataTextField = "TimeName";
        DD_time_zone.DataValueField = "TimeID";
        DD_time_zone.DataBind();

        DataRow[] dr_timezone = dt_defaultvalues.Select("mem_id = 'timezone'"); // Added by 'Imran Gani' on 28-Feb-2014, for user default values
        if (dr_timezone.Length > 0)
            DD_time_zone.Items.FindByValue(dr_timezone[0]["mem_value1"].ToString()).Selected = true;

        strSql = "select p_obj.code as [ConID], p_obj.name as [ConName]" +
                    " from sy_country p_obj where 1=1 order by ConName";

        DD_country.DataSource = HDD.GetDataTable(strSql);
        DD_country.DataTextField = "ConName";
        DD_country.DataValueField = "ConID";
        DD_country.DataBind();

        DataRow[] dr_country = dt_defaultvalues.Select("mem_id = 'country'"); // Added by 'Imran Gani' on 28-Feb-2014, for user default values
        if (dr_country.Length > 0)
            DD_country.Items.FindByValue(dr_country[0]["mem_value1"].ToString()).Selected = true;

        strSql = "select p_obj.c_code as [CurrID], p_obj.c_name as [CurrName]" +
            " from sy_currency p_obj where 1=1 order by CurrName";

        DD_currency_id.DataSource = HDD.GetDataTable(strSql);
        DD_currency_id.DataTextField = "CurrName";
        DD_currency_id.DataValueField = "CurrID";
        DD_currency_id.DataBind();

        DataRow[] dr_currency = dt_defaultvalues.Select("mem_id = 'currency'"); // Added by 'Imran Gani' on 28-Feb-2014, for user default values
        if (dr_currency.Length > 0)
            DD_currency_id.Items.FindByValue(dr_currency[0]["mem_value1"].ToString()).Selected = true;

        strSql = "select p_obj.af_row_id as [TitleID], p_obj.title as [TitleName]" +
            " from sy_org_structure p_obj where 1=1 order by TitleName";

        DD_title.DataSource = HDD.GetDataTable(strSql);
        DD_title.DataTextField = "TitleName";
        DD_title.DataValueField = "TitleID";
        DD_title.DataBind();

        strSql = "select mem_id, mem_name from sy_acr_mem where acr_id = '14ac6b9ce3a0e0f5' order by mem_name";

        DD_theme.DataSource = HDD.GetDataTable(strSql);
        DD_theme.DataTextField = "mem_name";
        DD_theme.DataValueField = "mem_id";
        DD_theme.DataBind();

        strSql = "select mem_id, mem_name from sy_acr_mem where acr_id = '521e7fc58f2c1029' order by mem_name";
        
        DD_custodian_filter.DataSource = HDD.GetDataTable(strSql);
        DD_custodian_filter.DataTextField = "mem_name";
        DD_custodian_filter.DataValueField = "mem_id";
        DD_custodian_filter.DataBind();

        strSql = "select p_obj.af_row_id as [ID], p_obj.menu_name as [Name]" +
            " from sy_mnu p_obj order by Name";

        string strsecurity = HDD.GetColumnValue("select is_security_applied from sy_bnd where af_row_id ='cc76a8f63812dcc9'").Trim();
        bool issecurity = strsecurity.Trim() == "" ? false : Convert.ToBoolean(strsecurity);
        if (issecurity)
        {
            strSql = applysecurity(strSql);
        }


        DD_home_page_menu.DataSource = HDD.GetDataTable(strSql);
        DD_home_page_menu.DataTextField = "Name";
        DD_home_page_menu.DataValueField = "ID";
        DD_home_page_menu.DataBind();
        DD_home_page_menu.Items.Add(new ListItem("", ""));
        DD_home_page_menu.SelectedValue = "";

        strSql = "select mem_id, mem_name from sy_acr_mem where acr_id = '5937020e4add150Y' order by mem_name";
        
        DD_hint_question.DataSource = HDD.GetDataTable(strSql);
        DD_hint_question.DataTextField = "mem_name";
        DD_hint_question.DataValueField = "mem_id";
        DD_hint_question.DataBind();

        strSql = "select p_obj.af_row_id as [ID], p_obj.role_name as [Name]" +
            " from sy_rol p_obj where 1=1 order by Name";

        //DD_role_id.DataSource = HDD.GetDataTable(strSql,true);
        DD_role_id.DataSource = HDD.GetDataTable(strSql); // Added by srivatsan
        DD_role_id.DataTextField = "Name";
        DD_role_id.DataValueField = "ID";
        DD_role_id.DataBind();
        //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
        strSql = "select bu_id,isnull(bu_id,bu_id) [desc]  from sy_bu_unit order by bu_desc";
        DD_buid.DataSource = HDD.GetDataTable(strSql);
        DD_buid.DataTextField = "desc";
        DD_buid.DataValueField = "bu_id";
        DD_buid.DataBind();
        //DD_buid.Items.Insert(0, new ListItem("--Select--", "")); // commented by 'Imran Gani' on 15-Sep-2014, to avoid empty value of business unit

        if (Session["userid"].ToString() != "afadmin")
        {
            for (int i = DD_buid.Items.Count - 1; i >= 0; i--)
            {
                if (DD_buid.Items[i].Text == "CS" || DD_buid.Items[i].Text == "ABC" || DD_buid.Items[i].Text == "rootNode")
                    DD_buid.Items.RemoveAt(i);
            }
        }
        DD_buid.SelectedValue = "MyCompany";
        DataTable dt_AcrBuUnit = HDD.GetDataTable("select * from sy_acr_mem where acr_id='f3e418cf75068a66' order by mem_seq asc;");
        RB_accessrights.Items.Add(new ListItem(Convert.ToString(dt_AcrBuUnit.Rows[0]["mem_name"]), Convert.ToString(dt_AcrBuUnit.Rows[0]["mem_value1"])));
        RB_accessrights.SelectedValue = Convert.ToString(dt_AcrBuUnit.Rows[0]["mem_value1"]);
        RB_accessrights.Items.Add(new ListItem(Convert.ToString(dt_AcrBuUnit.Rows[1]["mem_name"]), Convert.ToString(dt_AcrBuUnit.Rows[1]["mem_value1"])));
        RB_accessrights.Items.Add(new ListItem(Convert.ToString(dt_AcrBuUnit.Rows[2]["mem_name"]), Convert.ToString(dt_AcrBuUnit.Rows[2]["mem_value1"])));
        //----------------End for Org Security------------------
        if (Session["user_afrowid"].ToString() != "e51e0327224a2eb9") // Added to remove afadmin role if logged in person is not afadmin
        {
            //if (DD_role_id.Items.FindByText("afadmin:accessrights") != null)
            //    DD_role_id.Items.Remove(DD_role_id.Items.FindByText("afadmin:accessrights"));
            if (DD_role_id.Items.FindByValue("e7029dafbe379f85") != null) // Added by 'Imran Gani' on 08-May2014, to avoid role_id
                DD_role_id.Items.Remove(DD_role_id.Items.FindByValue("e7029dafbe379f85"));
            
        }



        LoadFormatMask();
    }


    private void LoadWizardUserEdit()
    {
        HDD = new HDDatabase();
        TB_user_id.Text = Server.HtmlDecode(strPageKey);

        //added by Sampath on 10-Nov-2011 for Encoding
        if (Request.QueryString["CPY"] != null)
        {
            TB_user_id.Enabled = true;
            CB_Active.Checked = true;
        }
        else
        {
            TB_user_id.Enabled = true;
        }

        string strSql = "Select * from sy_usr where user_id = '" + strPageKey.Replace("'", "''") + "'";
        DataRow dtaPageObj = HDD.GetTableRow(strSql);

        if (dtaPageObj != null)
            //CommonFunctions.decodeData(dtaPageObj);

        TB_last_name.Text = dtaPageObj["last_name"].ToString();
        TB_first_name.Text = dtaPageObj["first_name"].ToString();
        TB_mid_initial.Text = dtaPageObj["mid_initial"].ToString();
        DD_country.SelectedValue = dtaPageObj["country"].ToString();
        try
        {
            if (dtaPageObj["locale"].ToString().Length > 0)
                DD_Locale.SelectedValue = dtaPageObj["locale"].ToString();
        }
        catch (Exception e)//can be ignored, caused by storing neutral cultures in build 12
        {
        }
        DD_time_zone.SelectedValue = dtaPageObj["time_zone"].ToString();
        DD_currency_id.SelectedValue = dtaPageObj["currency_id"].ToString();
        DD_title.SelectedValue = dtaPageObj["title"].ToString();
        DD_theme.SelectedValue = dtaPageObj["Theme"].ToString();
        DD_custodian_filter.SelectedValue = dtaPageObj["custodian_filter"].ToString();
        DD_home_page_menu.SelectedValue = dtaPageObj["home_page_menu"].ToString();
        HF_created_by.Value = dtaPageObj["created_by"].ToString();
        HF_owner_id.Value = dtaPageObj["owner_id"].ToString();// Added by srivatsan on June 15 2009 for owner id field
        ownerid.Value = dtaPageObj["owner_id"].ToString();
        HF_created_at.Value = dtaPageObj["created_at"].ToString();
        DD_Default_Dashboard.SelectedValue = dtaPageObj["default_dashboard"].ToString();

        TB_email_id.Text = dtaPageObj["email_id"].ToString();
        //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
        DataTable dt_BuUnit = HDD.GetDataTable("select bu_id  from sy_bu_unit where af_row_id='" + dtaPageObj["bu_id"].ToString() + "'");
        if (dt_BuUnit != null & dt_BuUnit.Rows.Count > 0)
        {
            DD_buid.SelectedValue = Convert.ToString(dt_BuUnit.Rows[0]["bu_id"]);
        }
        else
            DD_buid.SelectedIndex = 0;
        RB_accessrights.SelectedValue = dtaPageObj["access_rights"].ToString();
        if (dtaPageObj["chk_bu_unit"].ToString() != "" && Convert.ToBoolean(dtaPageObj["chk_bu_unit"]))
        {
            CB_bu_unit.Checked = true;
        }
        if (dtaPageObj["chk_reporting_to"].ToString() != "" && Convert.ToBoolean(dtaPageObj["chk_reporting_to"]))
        {
            CB_reporting_to.Checked = true;
        }
        //----------------End for Org Security------------------
        if (Request.QueryString["PK"] != null)
        {
            //ddownerid.SelectedValue = dtaPageObj["owner_id"].ToString();
            CB_Active.Checked = Convert2Bool(dtaPageObj["active"].ToString());
            ownerid.Value = dtaPageObj["owner_id"].ToString();
            LoadEditPage LEP = new LoadEditPage();
            txt_ownerid.Text = LEP.GetUserIDFromAfrowid(dtaPageObj["owner_id"].ToString());
            LEP = null;
            if (Request.QueryString["CPY"] != null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                ownerid.Value = Session["user_afrowid"].ToString();
                txt_ownerid.Text = Session["userid"].ToString();
            }
        }
        else
        {
            //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
            ownerid.Value = Session["user_afrowid"].ToString();
            txt_ownerid.Text = Session["userid"].ToString();
            CB_Active.Checked = true;
        }
        //ddownerid.SelectedValue = dtaPageObj["owner_id"].ToString();

        TB_password.Text = dtaPageObj["password"].ToString();

        DD_hint_question.SelectedValue = dtaPageObj["hint_question"].ToString();
        TB_hint_answer.Text = dtaPageObj["hint_answer"].ToString();

        strSql = "Select * from sy_usr_rol where user_id = '" + ps_rowkey.Value + "'";
        DataRow dr1 = HDD.GetTableRow(strSql);
        DD_role_id.SelectedValue = dr1["role_id"].ToString();

        HF_user_role_rowkey.Value = dr1["af_row_id"].ToString();

        strSql = " Select p_obj.af_row_id as [CurrID], p_obj.user_id as [CurrName] from sy_usr p_obj where " +
                 " title in (Select sy_org_structure.reporting_title " +
                 " from sy_org_structure where sy_org_structure.af_row_id = '" + DD_title.SelectedValue + "') order by CurrName";

        DD_reporting_to.DataSource = HDD.GetDataTable(strSql);
        DD_reporting_to.DataTextField = "CurrName";
        DD_reporting_to.DataValueField = "CurrID";
        DD_reporting_to.DataBind();
        DD_reporting_to.Items.Add("");

        DataTable dt_FN = HDD.GetDataTable("Select * from sy_org_structure");
        string temp_org = "";
        string temp_rep = DD_title.SelectedValue;
        bool bln_end = false;
        int counter = 0; // added for cyclic reference
        do
        {
            DataRow[] dr = dt_FN.Select("af_row_id = '" + temp_rep + "'");
            if (dr.Length > 0)
            {
                if (dr[0]["reporting_title"].ToString() != "")
                {
                    temp_org = temp_org + "'" + dr[0]["reporting_title"].ToString() + "',";
                    temp_rep = dr[0]["reporting_title"].ToString();
                }
                else
                {
                    bln_end = true;
                }
            }
            else
            {
                bln_end = true;
            }
            if (counter >= dt_FN.Rows.Count) //added for cyclic reference
                bln_end = true;
            counter += 1;
        } while (!bln_end);

        if (temp_org.Length > 0)
            temp_org = temp_org.Substring(0, temp_org.LastIndexOf(","));

        strSql = "Select p_obj.af_row_id as [CurrID], p_obj.user_id as [CurrName] from sy_usr p_obj where " +
                        " title in (" + temp_org + ")";

        DD_reporting_to.DataSource = HDD.GetDataTable(strSql);
        DD_reporting_to.DataTextField = "CurrName";
        DD_reporting_to.DataValueField = "CurrID";
        DD_reporting_to.DataBind();
        DD_reporting_to.Items.Add("");

        DD_reporting_to.SelectedValue = dtaPageObj["reporting_to"].ToString();
    }

    private void LoadFormatMask()
    {
        try
        {
            HDD = new HDDatabase();
            PageCommonFunctions PCF = new PageCommonFunctions();
            string strSql = "";
            string inputMask = "";
            string strPageId = "p_usr";
            HtmlTableCell hc;
            DDI = new DynamicDisplayI();
            strSql = "select A.* from sy_pg_ctr A INNER JOIN sy_pg B on A.page_id = B.af_row_id where B.page_id = '" + strPageId.Replace("'", "''") + "' order by page_id,control_seq asc";
            DataTable dtaPageCtrl = HDD.GetDataTable(strSql);

            foreach (DataRow dr in dtaPageCtrl.Rows)
            {
                inputMask = dr["input_mask_format"].ToString();
                if (inputMask != "")
                {
                    hc = (HtmlTableCell)DDI.FindControl(frmObj.Controls, "hc_" + dr["control_html"].ToString() + "_" + dr["control_attrib_id"].ToString());
                    if (hc != null)
                    {
                        switch (dr["control_html"].ToString().ToUpper())
                        {
                            case "DA":
                                break;
                            case "DT":
                                break;
                            case "TB":
                                TextBox txt = (TextBox)DDI.FindControl(frmObj.Controls, dr["control_html"].ToString() + "_" + dr["control_attrib_id"].ToString());
                                PCF.processInputMask(ref hc, txt, inputMask);
                                break;
                            case "CB":
                                break;
                            case "DD":
                                break;
                            case "PW":
                            case "ENC":
                                TextBox pwtxt = (TextBox)DDI.FindControl(frmObj.Controls, dr["control_html"].ToString() + "_" + dr["control_attrib_id"].ToString());
                                PCF.processInputMask(ref hc, pwtxt, inputMask);
                                break;
                        }
                    }
                }
            }
            PCF = null;
            dtaPageCtrl = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in LoadFormatMask: " + e.Message);
        }
    }

    protected void DD_title_SelectedIndexChanged(object sender, EventArgs e)
    {
        //DataTable dt_FN = HDD.GetDataTable("Select * from sy_org_structure");
        //string temp_org = "";
        //string temp_rep = DD_title.SelectedValue;
        //bool bln_end = false;

        //do
        //{
        //    DataRow[] dr = dt_FN.Select("af_row_id = '" + temp_rep + "'");
        //    if (dr.Length > 0)
        //    {
        //        if (dr[0]["reporting_title"].ToString() != "")
        //        {
        //            temp_org = temp_org + "'" + dr[0]["reporting_title"].ToString() + "',";
        //            temp_rep = dr[0]["reporting_title"].ToString();
        //        }
        //        else
        //        {
        //            bln_end = true;
        //        }
        //    }
        //} while (!bln_end);

        //if (temp_org.Length >0)
        //    temp_org = temp_org.Substring(0, temp_org.LastIndexOf(","));

        //string strSql = "Select p_obj.af_row_id as [CurrID], p_obj.user_id as [CurrName] from sy_usr p_obj where " +
        //                " title in (" + temp_org + ") order by CurrName";

        //DD_reporting_to.DataSource = HDD.GetDataTable(strSql);
        //DD_reporting_to.DataTextField = "CurrName";
        //DD_reporting_to.DataValueField = "CurrID";
        //DD_reporting_to.DataBind();
        //DD_reporting_to.Items.Add("");
        LoadReportingTo();
    }

    private void LoadReportingTo()
    {
        try
        {
            DD_reporting_to.Items.Clear();
            DataTable dt_FN = HDD.GetDataTable("Select * from sy_org_structure");
            string temp_org = "";
            string temp_rep = DD_title.SelectedValue;
            bool bln_end = false;
            int counter = 0; // added for cyclic reference
            do
            {
                DataRow[] dr = dt_FN.Select("af_row_id = '" + temp_rep + "'");
                if (dr.Length > 0)
                {
                    if (dr[0]["reporting_title"].ToString() != "")
                    {
                        temp_org = temp_org + "'" + dr[0]["reporting_title"].ToString() + "',";
                        temp_rep = dr[0]["reporting_title"].ToString();
                    }
                    else
                    {
                        bln_end = true;
                    }
                }
                else //added for cyclic reference
                {
                    bln_end = true;
                }
                if (counter >= dt_FN.Rows.Count)
                    bln_end = true;
                counter += 1;
            } while (!bln_end);

            if (temp_org.Length > 0)
                temp_org = temp_org.Substring(0, temp_org.LastIndexOf(","));

            string strSql = "Select p_obj.af_row_id as [CurrID], p_obj.user_id as [CurrName] from sy_usr p_obj where " +
                            " title in (" + temp_org + ") order by CurrName";

            DD_reporting_to.DataSource = HDD.GetDataTable(strSql);
            DD_reporting_to.DataTextField = "CurrName";
            DD_reporting_to.DataValueField = "CurrID";
            DD_reporting_to.DataBind();
            DD_reporting_to.Items.Add("");
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("LoadReportingTo : Error : " + ex.Message);
        }
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    private void setSessionVariables()
    {
        try
        {
            if (Session["user_afrowid"] != null)
                if (Session["user_afrowid"].ToString() == ps_rowkey.Value)
                    Session["userlocale"] = DD_Locale.SelectedValue;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setSessionVariables. " + e.Message);
        }
    }
    private Label getMessageLabel()//included by sanal on Dec 21, 2010
    {
        DynamicDisplayI ddi = null;
        Label lblRet = new Label();
        try
        {
            ddi = new DynamicDisplayI();
            Control c = ddi.FindControl(User_Wizard.Parent.Controls,"lblMessage");
            if (c!=null)
            {
                if (c is Label)
                {
                lblRet = (Label)c;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error :getMessageLabel " + e.Message);
        }
        finally { ddi = null; }
        return lblRet;
    }
    protected void User_Wizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        //Control c = User_Wizard.FindControl("");
        Label lbl_message = getMessageLabel();
        if (!validatePassword(ref lbl_message)) // Added by 'Imran Gani' on 25-Nov-2013.
            return;
        if (!validateOwnerid(ref lbl_message))
            return;
        string isexits = HDD.GetColumnValue("sy_usr", "user_id", "user_id = '" + TB_user_id.Text.Replace("'", "''") + "'");
        string bCheckAllCompanies = HDD.GetColumnValue("select mem_value1 from sy_acr_mem where af_row_id='ddb82473faa8c2c2'");
        if (bCheckAllCompanies.ToLower() == "true")
        {
            HDDatabase hdserver = new HDDatabase(Session["servercon"].ToString());
            isexits = hdserver.GetColumnValue("select user_id from ngcompanyuser where user_id='" + TB_user_id.Text.Replace("'", "''") + "'");
        }
        if ((IsCopy == true) || (IsEdit == false))
        {
            if (isexits.Trim().Length > 0)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;User already exists.",true);
                e.Cancel = true;
            }
            else
            {
                GetGridRows();
                if (SaveData(ref lbl_message))
                {
                    //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                    if (!this.HDD.ExecuteTransaction(this.DeleteAndInsertTreeViewBUUnit()))
                    {
                        lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Business Unit Insert not successful. " + ErrorMessage, true);
                    }
                    //----------------End for Org Security------------------
                    lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Inserted Successfully", false);//changed by prithi on 07-Aug-2008
                    Session["dseTempInputInfo"] = null;
                    Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '8c2cb032c3b3516d' and pageset_url = 'UserWizard.aspx'") + "&pgs_id=8c2cb032c3b3516d"); // pageset_id and pgs_id = 'ps_user'
                }
                else
                {
                    lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + ErrorMessage,true);
                }
            }
        }
        else
        {
            if (bCheckAllCompanies.ToLower() == "true")
            {
                HDDatabase hdserver = new HDDatabase(Session["servercon"].ToString());
                string sUserid = HDD.GetColumnValue("sy_usr", "user_id", "af_row_id = '" + Request.QueryString["PK"].ToString() + "'");
                if (TB_user_id.Text != sUserid)
                {
                    if (hdserver.GetDataTable("select user_id from ngcompanyuser where user_id='" + TB_user_id.Text.Replace("'", "''") + "'").Rows.Count > 0)
                    {
                        lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;User already exists.",true);
                        hdserver = null;
                        return;
                    }
                    hdserver = null;
                }
            }
            GetGridRows();
            if (SaveData(ref lbl_message))
            {
                //if (strPageKey.ToLower().Trim() != TB_user_id.Text.ToLower().Trim())
                //{
                //    isUseridEmailFormat(dseInputInfo.Tables["p_usr"].Rows[0]);    
                //}
                //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                if (!this.HDD.ExecuteTransaction(this.DeleteAndInsertTreeViewBUUnit()))
                {
                    lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Business Unit Insert not successful. " + ErrorMessage, true);
                }
                //----------------End for Org Security------------------
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data Inserted Successfully",false);//changed by prithi on 07-Aug-2008
                Session["dseTempInputInfo"] = null;
                Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '8c2cb032c3b3516d' and pageset_url = 'UserWizard.aspx'") + "&pgs_id=8c2cb032c3b3516d"); // pageset_id and pgs_id = 'ps_user'
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + ErrorMessage,true);
            }
        }
    }

    public bool GetGridRows()
    {
        bool blnStatus = true;
        DataRow droPageData;
        HDD = new HDDatabase();
        DDI = new DynamicDisplayI();
        DataSet dseInputInfo = new DataSet();
        string[,] pagearr = pagearr = new string[,] 
            {
                {"User", "8c2cb032c3b3516d"}, // ps_user
                {"User", "9d36fd7489029c87"}, // ps_user_rol
            };

        string strPagesetRowID = "";
        string strPageId = "";
        //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
        DataTable dt_BusinessUnit = this.HDD.GetDataTable("select * from sy_bu_unit");
        //----------------End for Org Security------------------

        for (int p = 0; p <= pagearr.GetUpperBound(0); p++)
        {
            strPagesetRowID = pagearr[p, 1].ToString();

            ScreenReader SR = new ScreenReader();
            Master MA = new Master();
            PageInfoLoad PIL = new PageInfoLoad();

            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);

            DataTable dtaPageSet = dsePageInfo.Tables["PageSet"];
            DataTable dtaPage = dsePageInfo.Tables["Page"];
            DataTable dtaPageKeys = dsePageInfo.Tables["PageKeys"];
            DataTable dtaPageCtrl = dsePageInfo.Tables["PageCtrl"];

            if (dseTempInputInfo.Tables.Contains(dtaPage.Rows[0]["page_id"].ToString()) == false)
                SR.CreatePageDataTable(dseTempInputInfo, dtaPage, dtaPageCtrl);

            for (int i = 0; i < dtaPage.Rows.Count; i++)
            {
                strPageId = dtaPage.Rows[i]["page_id"].ToString();

                if (strPageId == "p_usr")
                {
                    dseTempInputInfo.Tables[strPageId].Clear();
                    droPageData = dseTempInputInfo.Tables[strPageId].NewRow();

                    droPageData["af_row_id"] = ps_rowkey.Value == "" ? SR.getHashKey() : ps_rowkey.Value;
                    droPageData["user_id"] = TB_user_id.Text;

                    droPageData["last_name"] = TB_last_name.Text;
                    droPageData["first_name"] = TB_first_name.Text;
                    droPageData["mid_initial"] = TB_mid_initial.Text;

                    droPageData["country"] = DD_country.SelectedValue;
                    droPageData["locale"] = DD_Locale.SelectedValue;

                    if ((IsEdit) && (!IsCopy))
                    {
                        droPageData["password"] = HF_password.Value;
                    }
                    else
                    {
                        droPageData["password"] = security.encrypt(TB_password.Text);
                    }
                    droPageData["time_zone"] = DD_time_zone.SelectedValue;

                    droPageData["currency_id"] = DD_currency_id.SelectedValue;
                    droPageData["theme"] = DD_theme.SelectedValue;
                    droPageData["title"] = DD_title.SelectedValue;

                    droPageData["reporting_to"] = DD_reporting_to.SelectedValue;
                    droPageData["custodian_filter"] = DD_custodian_filter.SelectedValue;
                    droPageData["home_page_menu"] = DD_home_page_menu.SelectedValue;

                    droPageData["hint_question"] = DD_hint_question.SelectedValue;
                    droPageData["hint_answer"] = TB_hint_answer.Text;

                    droPageData["created_by"] = HF_created_by.Value == "" ? SR.getHashKey() : HF_created_by.Value;
                    //droPageData["owner_id"] = HF_owner_id.Value == "" ? SR.getHashKey() : HF_owner_id.Value;// Added by srivatsan on June 15 2009 for owner id field 
                    droPageData["owner_id"] = ownerid.Value == "" ? "" : ownerid.Value;// Added by srivatsan on June 15 2009 for owner id field 
                    droPageData["created_at"] = HF_created_at.Value == "" ? SR.getHashKey() : HF_created_at.Value;

                    droPageData["active"] = CB_Active.Checked;

                    droPageData["email_id"] = TB_email_id.Text;
                    droPageData["default_dashboard"] = DD_Default_Dashboard.SelectedValue;

                    //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
                    droPageData["access_rights"] = RB_accessrights.SelectedValue;
                    if (DD_buid.SelectedValue != "")
                        droPageData["bu_id"] = dt_BusinessUnit.Select("bu_id='" + DD_buid.SelectedValue.Replace("'", "''") + "'")[0]["af_row_id"];
                    if (CB_bu_unit.Checked)
                    {
                        droPageData["chk_bu_unit"] = "True";
                    }
                    else
                    {
                        droPageData["chk_bu_unit"] = "False";
                    }
                    if (CB_reporting_to.Checked)
                    {
                        droPageData["chk_reporting_to"] = "True";
                    }
                    else
                    {
                        droPageData["chk_reporting_to"] = "False";
                    }
                    //----------------End for Org Security------------------
                    dseTempInputInfo.Tables[strPageId].Rows.Add(droPageData);
                }
                else if (strPageId == "p_usr_rol")
                {
                    dseTempInputInfo.Tables[strPageId].Clear();
                    droPageData = dseTempInputInfo.Tables[strPageId].NewRow();

                    droPageData["af_row_id"] = HF_user_role_rowkey.Value == "" ? SR.getHashKey() : HF_user_role_rowkey.Value;
                    droPageData["user_id"] = ps_rowkey.Value;
                    droPageData["role_id"] = DD_role_id.SelectedValue;
                    droPageData["created_by"] = HF_created_by.Value == "" ? SR.getHashKey() : HF_created_by.Value;
                    droPageData["owner_id"] = ownerid.Value == "" ? "" : ownerid.Value;// Added by srivatsan on June 15 2009 for owner id field
                    droPageData["created_at"] = HF_created_at.Value == "" ? SR.getHashKey() : HF_created_at.Value;

                    dseTempInputInfo.Tables[strPageId].Rows.Add(droPageData);
                }
            }
        }

        Session["dseTempInputInfo"] = dseTempInputInfo;
        return blnStatus;
    }


    private bool SaveData(ref Label lbl_message)
    {

        if (!validateOwnerid(ref lbl_message))
        {
            return false;
        }
        bool blnStatus = true;
        DataSet dsetempInfo;
        Master MA = new Master();

        string strPagesetRowID = "";

        string[,] pagearr = pagearr = new string[,] 
            {
                {"User", "8c2cb032c3b3516d"}, // ps_user
                {"User", "9d36fd7489029c87"}, // ps_user_rol
            };
        PageInfoLoad PIL = new PageInfoLoad();
        dsePageInfo = new DataSet();
        dseInputInfo = new DataSet();

        dsePageInfo = PIL.GetPageSetPageCtrlInfo("8c2cb032c3b3516d"); // ps_user

        for (int j = 1; j <= pagearr.GetUpperBound(0); j++)
        {
            dsetempInfo = new DataSet();
            strPagesetRowID = pagearr[j, 1].ToString();
            dsetempInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
            dsePageInfo.Tables["Page"].Merge(dsetempInfo.Tables["Page"]);
            dsePageInfo.Tables["PageCtrl"].Merge(dsetempInfo.Tables["PageCtrl"]);
            dsePageInfo.Tables["PageKeys"].Merge(dsetempInfo.Tables["PageKeys"]);
        }

        dseInputInfo.Merge(dseTempInputInfo, true);
        //added by Sampath on 10-Nov-2011 for Encoding
        //CommonFunctions.encodeData(dseInputInfo);

        DefaultColumnUpdate();

        if ((IsEdit) && (!IsCopy))
        {
            GlobalValues.dsAudit.Tables.Add(HDD.GetDataTable("Select * from sy_usr where user_id = '" + strPageKey.Replace("'", "''") + "'", "p_usr").Copy());
            GlobalValues.dsAudit.Tables.Add(HDD.GetDataTable("Select * from sy_usr_rol where user_id = '" + ps_rowkey.Value + "'", "p_usr_rol").Copy());
            blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        }
        else
        {
            blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        }
        this.strErrMessage = MA.ErrorMessage;
        return blnStatus;
    }

    private void DefaultColumnUpdate()
    {
        string strPageId = "";
        string[,] pagearr = pagearr = new string[,] 
            {
                {"User", "p_usr"},
                {"User", "p_usr_rol"},
            };

        for (int j = 0; j <= pagearr.GetUpperBound(0); j++)
        {
            strPageId = pagearr[j, 1].ToString();
            foreach (DataRow dr in dseInputInfo.Tables[strPageId].Rows)
            {
                if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_date"))
                {
                    dr["modified_date"] = DateTime.Now.ToString();
                }
                else if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_at"))
                {
                    dr["modified_at"] = DateTime.Now.ToString();
                }

                if ((IsEdit) && (!IsCopy))
                {
                }
                else
                {
                    if (dseInputInfo.Tables[strPageId].Columns.Contains("created_date"))
                    {
                        dr["created_date"] = DateTime.Now.ToString();
                    }
                    else if (dseInputInfo.Tables[strPageId].Columns.Contains("created_at"))
                    {
                        dr["created_at"] = DateTime.Now.ToString();
                    }

                    ////new code added for QC Portal changes. mail by Omprakash, done by Sampath
                    //if (dseInputInfo.Tables[strPageId].Columns.Contains("is_using_sys_pwd"))
                    //{
                    //    dr["is_using_sys_pwd"] = "0";
                    //}
                }

                if (dseInputInfo.Tables[strPageId].Columns.Contains("modified_by"))
                {
                    dr["modified_by"] = HttpContext.Current.Session["user_afrowid"].ToString();
                }

                if ((IsEdit) && (!IsCopy))
                {
                }
                else
                {
                    if (dseInputInfo.Tables[strPageId].Columns.Contains("created_by"))
                    {
                        dr["created_by"] = HttpContext.Current.Session["user_afrowid"].ToString();
                    }

                }

                if (dseInputInfo.Tables[strPageId].Columns.Contains("owner_id")) // Added by srivatsan on June 15 2009 for owner id field
                {
                    //dr["owner_id"] = HttpContext.Current.Session["user_afrowid"].ToString();
                    //dr["owner_id"] = ddownerid.SelectedValue;
                    //dr["owner_id"] = ownerid.Value;
                }//
            }
        }
    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    protected void User_Wizard_CancelButtonClick(object sender, EventArgs e)
    {
        Session["dseTempInputInfo"] = null;
        Response.Redirect("DisplayGrid.aspx?mn=" + HDD.GetColumnValue("sy_mnu", "af_row_id", "pageset_id = '8c2cb032c3b3516d' and pageset_url = 'UserWizard.aspx'") + "&pgs_id=8c2cb032c3b3516d"); // pageset_id and pgs_id = 'ps_user'
    }
    private void getpageicons() // added by srivatsan to get page icons
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            //wz_Report.HeaderText = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + wz_Report.HeaderText;
            Label lblcontrol = (Label)this.Master.FindControl("ctl00$ContentPlaceHolder3$User_Wizard$HeaderContainer$lblTopHeader");
            lblcontrol.Text = "&nbsp;" + icons.geticontextfrompageset(Request.QueryString["pgs_id"].ToString(), 2) + "&nbsp;" + lblcontrol.Text;

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            //wz_Report.HeaderText = "&nbsp;<img src =Images/MBIcons/small/default.gif><img>&nbsp;"+ wz_Report.HeaderText;

        }
        finally
        {
            icons = null;
            HDD = null;
        }
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            //string bindid = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            ////BC.Bind(bindid, ddownerid, ref dt);
            //string sql = "select af_row_id,user_id from sy_usr where af_row_id <> 'e51e0327224a2eb9' order by user_id";
            //DataSet ds = new DataSet();
            //ds = Hdd.GetDataset(sql);

            //if (ds != null)
            //{
            //    if (ds.Tables.Count > 0)
            //    {
            //        if (ds.Tables[0].Rows.Count > 0)
            //        {
            //            ddownerid.DataSource = ds.Tables[0];
            //            ddownerid.DataTextField = "user_id";
            //            ddownerid.DataValueField = "af_row_id";
            //            ddownerid.DataBind();
            //            //ddownerid.DataValueField = ds.Tables[0].Ro
            //        }
            //    }
            //}

            //if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
            //{
            //    ddownerid.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
            //}

            if (Request.QueryString["PK"] == null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                ownerid.Value = Session["user_afrowid"].ToString();
                txt_ownerid.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                    ownerid.Value = Session["user_afrowid"].ToString();
                    txt_ownerid.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }


    private bool validateOwnerid(ref Label lbl_message)
    {
        bool status = false;
        BindControl BC = new BindControl();
        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
        if (dsBind != null)
        {
            if (dsBind.Tables.Count > 0)
            {
                if (dsBind.Tables[0].Rows.Count > 0)
                {
                    if (txt_ownerid.Text != "")
                    {
                        DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_ownerid.Text.Trim().Replace("'", "''") + "'");

                        if (drrbind.Length > 0)
                        {
                            ownerid.Value = drrbind[0]["val"].ToString();
                            status = true;
                        }
                        else
                        {
                            if (txt_ownerid.Text.ToLower() == Session["userid"].ToString().ToLower())
                            {
                                ownerid.Value = Session["user_afrowid"].ToString();
                                txt_ownerid.Text = Session["userid"].ToString();
                                status = true;
                            }
                        }
                    }
                    else
                    {
                        ownerid.Value = "";
                        status = true;
                    }
                }
                else
                {
                    ownerid.Value = "";
                    status = true;
                }
            }
        }
        if (status != true)
        {
            //lbl_message.Text = "<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + txt_ownerid.Text;
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Invalid data for Owner :" + HttpUtility.HtmlEncode(txt_ownerid.Text),true);

        }
        return status;

    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

                txt_ownerid.Enabled = false;
                imgsearch.Visible = false;
            }

            sec = null;
        }
        catch
        {

        }
    }

    private string applysecurity(string sql)
    {

        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    sAFAdmin += " and " + sCustodianFilter;
                }
                else
                {
                    //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                    //{
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    //sAFAdmin += " " + sCustodianFilter;
                    // }
                }

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
                }
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql + " where " + sAFAdmin;
                }
            }


        }
        catch
        {

        }
        return sql;
    }

    private bool Convert2Bool(string strdata)
    {
        bool result = false;
        try
        {
            if (strdata != "")
            {
                result = Convert.ToBoolean(strdata);
            }
        }
        catch (Exception ex)
        {

        }
        return result;

    }

    private bool isUseridEmailFormat(DataRow drUser)
    {
        bool bReturn = true;

        String Is_Email = HDD.GetColumnValue("select mem_value1 from sy_acr_mem where af_row_id='3a2e30df98bba50Z'");

        if (Is_Email.ToLower() == "true")
        {
            String sNew_Email = getContent(HttpContext.Current.Server.MapPath("") + @"\UserId_Change_New.htm");
            String sFName = drUser["first_name"].ToString();
            String sLName = drUser["last_name"].ToString();
            if (sFName.ToLower().Trim() != sLName.ToLower().Trim())
            {
                sNew_Email = sNew_Email.Replace("$User", sFName + " " + sLName);
            }
            else
            {
                sNew_Email = sNew_Email.Replace("$User", sFName);
            }

            sNew_Email = sNew_Email.Replace("$Path$", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + HDD.GetColumnValue("select mem_value1 from sy_acr_mem where af_row_id='986382dcbe05703e'"));
            //String sOld_UserId = "";
            DataSet dsTemp = HDD.GetDataset("select * from sy_usr where af_row_id='" + Request.QueryString["PK"] + "';select * from sy_usr where af_row_id='650a333596bbf348'");
            //if (dsTemp.Tables[0].Rows.Count > 0)
            //{
            //    sOld_UserId = dsTemp.Tables[0].Rows[0]["user_id"].ToString();
            //}
            sNew_Email = sNew_Email.Replace("$old_user_id", strPageKey);
            sNew_Email = sNew_Email.Replace("$new_user_id", drUser["user_id"].ToString());
            String sAdminF = "";
            String sAdminL = "";
            String sAdminU = "";
            if (dsTemp.Tables[1].Rows.Count > 0)
            {
                sAdminF = dsTemp.Tables[1].Rows[0]["first_name"].ToString();
                sAdminL = dsTemp.Tables[1].Rows[0]["last_name"].ToString();
                sAdminU = dsTemp.Tables[1].Rows[0]["user_id"].ToString();
            }

            if (sAdminL.ToLower().Trim() != sAdminF.ToLower().Trim())
            {
                sNew_Email = sNew_Email.Replace("$Admin_fname", sAdminF);
                sNew_Email = sNew_Email.Replace("$Admin_lname", sAdminL);
            }
            else
            {
                sNew_Email = sNew_Email.Replace("$Admin_fname", sAdminF);
                sNew_Email = sNew_Email.Replace("$Admin_lname", "");
                sAdminL = "";
            }
            sNew_Email = sNew_Email.Replace("$Company_Name", Session["company_id"].ToString());


            CommonFunctions objCommFunc = new CommonFunctions();
            if (objCommFunc.sendEmail(drUser["user_id"].ToString(), sAdminU, sAdminF + " " + sAdminL, true, "Easy-Commission user id change", sNew_Email, null, null) == "success")
            {
                String sOld_Email = getContent(HttpContext.Current.Server.MapPath("") + @"\UserId_Change_Old.htm");

                if (sFName.ToLower().Trim() != sLName.ToLower().Trim())
                {
                    sOld_Email = sOld_Email.Replace("$User", sFName + " " + sLName);
                }
                else
                {
                    sOld_Email = sOld_Email.Replace("$User", sFName);
                }

                sOld_Email = sOld_Email.Replace("$old_user_id", strPageKey);
                sOld_Email = sOld_Email.Replace("$new_user_id", drUser["user_id"].ToString());

                if (sAdminL.ToLower().Trim() != sAdminF.ToLower().Trim())
                {
                    sOld_Email = sOld_Email.Replace("$Admin_fname", sAdminF);
                    sOld_Email = sOld_Email.Replace("$Admin_lname", sAdminL);
                }
                else
                {
                    sOld_Email = sOld_Email.Replace("$Admin_fname", sAdminF);
                    sOld_Email = sOld_Email.Replace("$Admin_lname", "");
                    sAdminL = "";
                }
                sOld_Email = sOld_Email.Replace("$Company_Name", Session["company_id"].ToString());

                if (objCommFunc.sendEmail(strPageKey.ToString(), sAdminU, sAdminF + " " + sAdminL, true, "Easy-Commission user id change", sOld_Email, null, null) == "success")
                {
                    bReturn = true;
                }
                else
                {
                    bReturn = false;
                }
            }
            else
            {
                bReturn = false;
            }

            objCommFunc = null;
        }



        return bReturn;
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName))
                return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close();
            sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    private void setHeaderText()
    {
        if (this.Master.FindControl("ctl00$ContentPlaceHolder3$User_Wizard$HeaderContainer$lblTopHeader") != null)
        {
            Label lblcontrol = (Label)this.Master.FindControl("ctl00$ContentPlaceHolder3$User_Wizard$HeaderContainer$lblTopHeader");

            if (Request.QueryString["PK"] != null)
            {
                lblcontrol.Text = "Users - Edit";
            }
            else
            {
                lblcontrol.Text = "Users - Add";
            }
            if (Request.QueryString["CPY"] != null)
            {
                lblcontrol.Text = "Users - Copy";
            }
            if (Request.QueryString["Vmode"] != null)
            {
                lblcontrol.Text = "Users - View";
            }
            //if(!Page.IsPostBack)
                if (drpage != null)
                    AddPageToolTip(drpage, ref lblcontrol);

        }

    }

    private void AddPageToolTip(DataRow drpage,ref Label lblHeader)
    {    
                    if (drpage!=null)
                    {
                        //if(!Page.IsPostBack)
                        lblHeader.Text = lblHeader.Text + getTootipIcon(drpage);
                        Literal lit = new Literal();
                        lit.Text = getTooltipContent(drpage);
                        td_Page_ToopTip.Controls.Add(lit);
                    }
    }
    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        //string ret = "";
        //ret = "<div id=\"page_tooltip_div\" style=\"border-bottom:solid 1px #000000;\">";
        //ret += "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"100%\"><tr><td width=\"10%\" valign=\"center\" align=\"center\"><img src=\"Images/info.gif\" border=\"0\"></img></td><td width=\"80%\" class=\"controlFont\">";
        //ret += droPage["page_desc"].ToString();
        //ret += "</td></tr></table>";
        //ret +="</div>";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }
    private DataRow GetPageDataRow()
    {
        DataRow drr = null;
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select * From sy_pg where af_row_id = 'c835cefdea0d7518'";
            drr = HDD.GetTableRow(sql);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetPageDataRow : "+ex.Message );
        }
        finally
        {
            HDD = null;
        }
        return drr;
    }
    private void LoadDashboards()
    {
        HDDatabase HDD = new HDDatabase();
        DataTable dt = new DataTable();
        try
        {
            string sql = "select Name,af_row_id from sy_dashboard_master where active = 1 order by Name";
            dt = HDD.GetDataTable(sql);
            if (dt != null)
            {
                DD_Default_Dashboard.DataSource = dt;
                DD_Default_Dashboard.DataTextField = "Name";
                DD_Default_Dashboard.DataValueField = "af_row_id";
                DD_Default_Dashboard.DataBind();

                DD_Default_Dashboard.Items.Insert(0, "");
            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadDashboards :" + ex.Message);
        }
        finally
        {
            HDD = null;
            dt = null;
        }

    }
    //-----------Added by 'Imran Gani' (copied from RakaTech) on 05-June-2013 for Org Security-----------
    #region Tree View Business Unit Generation
    private void LoadTreeView()
    {
        DataTable dt_AcrBuUnit = HDD.GetDataTable("select * from sy_acr_mem where acr_id='f3e418cf75068a66';");
        if (dt_AcrBuUnit != null && dt_AcrBuUnit.Rows.Count == 4)
        {
            BusinessUnit.Access ACS = new BusinessUnit.Access(strPageKey.Replace("'", "''"), HDD.GetConnection().ConnectionString, "");
            BusinessUnit.LoadToTreeView LTV = new BusinessUnit.LoadToTreeView();
            string str_RadioButton = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
                        + "<input  type='radio' name='RB_accessrights_" + LTV.ValueReplacer + "'  " + LTV.Visible + " id='RB_accessrights_" + LTV.ValueReplacer + "_1' "
                        + " value='" + dt_AcrBuUnit.Rows[0]["mem_value1"].ToString() + "' onchange=\"NodeSave(this,'" + LTV.ValueReplacer + "','" + LTV.TextReplacer + "');\" />"
                        + "<label class='controlFont' for='RB_accessrights_" + LTV.ValueReplacer + "_1'>" + dt_AcrBuUnit.Rows[0]["mem_name"].ToString() + "</label>"
                        + "<input type='radio'  name='RB_accessrights_" + LTV.ValueReplacer + "'  " + LTV.Visible + " id='RB_accessrights_" + LTV.ValueReplacer + "_0' "
                        + "value='" + dt_AcrBuUnit.Rows[1]["mem_value1"].ToString() + "' onchange=\"NodeSave(this,'" + LTV.ValueReplacer + "','" + LTV.TextReplacer + "'); \" />"
                        + "<label class='controlFont' for='RB_accessrights_" + LTV.ValueReplacer + "_0'>" + dt_AcrBuUnit.Rows[1]["mem_name"].ToString() + "</label>"
                        + "<input  type='radio' name='RB_accessrights_" + LTV.ValueReplacer + "'  " + LTV.Visible + " id='RB_accessrights_" + LTV.ValueReplacer + "_2' "
                        + " onchange=\"NodeSave(this,'" + LTV.ValueReplacer + "','" + LTV.TextReplacer + "'); \"  value='" + dt_AcrBuUnit.Rows[2]["mem_value1"].ToString() + "' />"
                        + "<label class='controlFont' for='RB_accessrights_" + LTV.ValueReplacer + "_2'>" + dt_AcrBuUnit.Rows[2]["mem_name"].ToString() + "</label>"
                        + "<input  type='radio' name='RB_accessrights_" + LTV.ValueReplacer + "' " + LTV.Visible + " id='RB_accessrights_" + LTV.ValueReplacer + "_3' "
                        + " onchange=\"NodeSave(this,'" + LTV.ValueReplacer + "','" + LTV.TextReplacer + "'); \"  value='" + dt_AcrBuUnit.Rows[3]["mem_value1"].ToString() + "'  />"
                        + "<label class='controlFont' for='RB_accessrights_" + LTV.ValueReplacer + "_3'>" + dt_AcrBuUnit.Rows[3]["mem_name"].ToString() + "</label>";
            LTV.AddSuffix = str_RadioButton;
            LTV.LoadTreeView(tv_BuUnitModel, ACS.BusinessUnitsTable);
        }
    }
    private void LoadValuesOnEdit()
    {
        DataTable dt_UserBusinessAccess = HDD.GetDataTable("select a.access_rights,b.bu_id,b.bu_desc,b.af_row_id from sy_usr_bu a,sy_bu_unit b where a.bu_id=b.af_row_id and  user_id='" + ps_rowkey.Value + "' order by b.bu_desc");
        HtmlTableRow htr_BuUnit = new HtmlTableRow();
        HtmlTableCell htc_BuUnit = new HtmlTableCell();
        foreach (DataRow dr_UserBusinessAccess in dt_UserBusinessAccess.Rows)
        {
            hih_SelectedTreeNode.Value += "#" + dr_UserBusinessAccess["bu_id"].ToString() + ":" + dr_UserBusinessAccess["af_row_id"].ToString() + ":" + dr_UserBusinessAccess["access_rights"].ToString() + "#";
        }
    }
    private void LoadValuesOnPostBack()
    {
        if (hih_SelectedTreeNode.Value != "")
        {
            htb_BuUnitGrid.Rows.Clear();
            HtmlTableRow htr_BuUnit = new HtmlTableRow();
            HtmlTableCell htc_BuUnit = new HtmlTableCell();
            htr_BuUnit.Attributes.Add("class", "Grid_Header");
            htc_BuUnit.Attributes.Add("class", "TreeGridViewStyle");
            htc_BuUnit.Controls.Add(new LiteralControl("Business Unit"));
            htr_BuUnit.Cells.Add(htc_BuUnit);
            htc_BuUnit = new HtmlTableCell();
            htc_BuUnit.Attributes.Add("class", "TreeGridViewStyle");
            htc_BuUnit.Controls.Add(new LiteralControl("Access Rights"));
            htr_BuUnit.Cells.Add(htc_BuUnit);
            htb_BuUnitGrid.Rows.Add(htr_BuUnit);

            foreach (string str_SelectVal in hih_SelectedTreeNode.Value.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries))
            {
                string[] strarrSelectedVal = str_SelectVal.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                htr_BuUnit = new HtmlTableRow();
                htc_BuUnit = new HtmlTableCell();
                htr_BuUnit.Attributes.Add("class", "Grid_Row0");
                htc_BuUnit.Attributes.Add("class", "TreeGridViewColumnStyle");
                htc_BuUnit.Controls.Add(new LiteralControl(strarrSelectedVal[0]));
                htr_BuUnit.Cells.Add(htc_BuUnit);
                htc_BuUnit = new HtmlTableCell();
                htc_BuUnit.Attributes.Add("class", "TreeGridViewColumnStyle");
                if (str_SelectVal.Contains(strarrSelectedVal[0] + ":" + strarrSelectedVal[1] + ":se"))
                {
                    htc_BuUnit.Controls.Add(new LiteralControl("Self"));
                }
                else if (str_SelectVal.Contains(strarrSelectedVal[0] + ":" + strarrSelectedVal[1] + ":un"))
                {
                    htc_BuUnit.Controls.Add(new LiteralControl("Unit"));
                }
                else if (str_SelectVal.Contains(strarrSelectedVal[0] + ":" + strarrSelectedVal[1] + ":su"))
                {
                    htc_BuUnit.Controls.Add(new LiteralControl("Unit & Subunits"));
                }
                htr_BuUnit.Cells.Add(htc_BuUnit);
                htb_BuUnitGrid.Rows.Add(htr_BuUnit);
            }
        }
        foreach (TreeNode Tn in tv_BuUnitModel.Nodes)
        {
            if (hih_SelectedTreeNode.Value.Contains(":" + Tn.Value + ":"))
            {
                this.BindBusinessUnts(Tn);
            }
            else
            {
                this.ReplaceTreeAccesRights(Tn, "_3", "_0", "_2", "_1");
            }
            this.LoadChildValuesOnPostBack(Tn);
        }
    }
    private void LoadChildValuesOnPostBack(TreeNode tn)
    {
        foreach (TreeNode tn_child in tn.ChildNodes)
        {
            if (hih_SelectedTreeNode.Value.Contains(":" + tn_child.Value + ":"))
            {
                this.BindBusinessUnts(tn_child);
            }
            else
            {
                this.ReplaceTreeAccesRights(tn_child, "_3", "_0", "_2", "_1");
            }
            if (tn_child.ChildNodes.Count > 0)
            {
                this.LoadChildValuesOnPostBack(tn_child);
            }
        }
    }
    private void BindBusinessUnts(TreeNode Tn)
    {
        foreach (string str_SelectVal in hih_SelectedTreeNode.Value.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries))
        {
            if (str_SelectVal.Contains(":" + Tn.Value + ":se"))
            {
                this.ReplaceTreeAccesRights(Tn, "_1", "_0", "_2", "_3");
                break;
            }
            else if (str_SelectVal.Contains(":" + Tn.Value + ":un"))
            {
                this.ReplaceTreeAccesRights(Tn, "_0", "_1", "_2", "_3");
                break;
            }
            else if (str_SelectVal.Contains(":" + Tn.Value + ":su"))
            {
                this.ReplaceTreeAccesRights(Tn, "_2", "_0", "_1", "_3");
                break;
            }
            else if (str_SelectVal.Contains(":" + Tn.Value + ":no"))
            {
                this.ReplaceTreeAccesRights(Tn, "_3", "_0", "_2", "_1");
                break;
            }
        }
    }
    private void ReplaceTreeAccesRights(TreeNode Tn, string str_true, string str_false1, string str_false2, string str_false3)
    {
        Tn.Text = Tn.Text.Replace("id='RB_accessrights_" + Tn.Value + str_true + "' ", "id='RB_accessrights_" + Tn.Value + str_true + "' checked='true' ");
        Tn.Text = Tn.Text.Replace("id='RB_accessrights_" + Tn.Value + str_false1 + "' checked='true' ", "id='RB_accessrights_" + Tn.Value + str_false1 + "' ");
        Tn.Text = Tn.Text.Replace("id='RB_accessrights_" + Tn.Value + str_false2 + "' checked='true' ", "id='RB_accessrights_" + Tn.Value + str_false2 + "' ");
        Tn.Text = Tn.Text.Replace("id='RB_accessrights_" + Tn.Value + str_false3 + "' checked='true' ", "id='RB_accessrights_" + Tn.Value + str_false3 + "' ");

    }
    private ArrayList DeleteAndInsertTreeViewBUUnit()
    {
        ArrayList arl_SelectedVal = new ArrayList();
        SqlCommand sco_BusinessUnit = new SqlCommand();
        DataTable dt_BusinessUnit = this.HDD.GetDataTable("select * from sy_bu_unit");
        DataTable dt_UserBuChk = this.HDD.GetDataTable("select user_id from sy_usr_bu where user_id='" + ps_rowkey.Value + "'");
        sco_BusinessUnit.CommandText = "delete from sy_usr_bu where user_id='" + ps_rowkey.Value + "'";
        arl_SelectedVal.Add(sco_BusinessUnit);
        string str_BusinessUnit = "";
        string str_BusinessUnitParam = "";
        ScreenReader SR;
        foreach (string str_SelectVal in hih_SelectedTreeNode.Value.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries))
        {
            string[] strarr_SelectedVal = str_SelectVal.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
            sco_BusinessUnit = new SqlCommand();
            SR = new ScreenReader();
            str_BusinessUnit = "insert into sy_usr_bu(user_id,af_row_id,bu_id,access_rights,modified_by,owner_id,modified_at,created_at";
            str_BusinessUnitParam = ") values(@user_id,@af_row_id,@bu_id,@access_rights,@modified_by,@owner_id,@modified_at,@created_at";
            sco_BusinessUnit.Parameters.AddWithValue("@user_id", ps_rowkey.Value);
            DataRow[] drarr_BuUnit = dt_BusinessUnit.Select("af_row_id='" + strarr_SelectedVal[1].ToString() + "'");
            sco_BusinessUnit.Parameters.AddWithValue("@bu_id", drarr_BuUnit[0]["af_row_id"].ToString());
            sco_BusinessUnit.Parameters.AddWithValue("@access_rights", strarr_SelectedVal[2].ToString());
            sco_BusinessUnit.Parameters.AddWithValue("@modified_at", DateTime.Now);
            sco_BusinessUnit.Parameters.AddWithValue("@modified_by", ownerid.Value);
            sco_BusinessUnit.Parameters.AddWithValue("@owner_id", ownerid.Value);
            HF_user_business_rowkey.Value = HF_user_business_rowkey.Value == "" ? SR.getHashKey() : HF_user_business_rowkey.Value;
            sco_BusinessUnit.Parameters.AddWithValue("@af_row_id", HF_user_business_rowkey.Value);
            //if (dt_UserBuChk != null && dt_UserBuChk.Rows.Count == 0)
            //{
            str_BusinessUnit += ",created_by";
            str_BusinessUnitParam += ",@created_by";

            sco_BusinessUnit.Parameters.AddWithValue("@created_by", ownerid.Value);
            // }
            sco_BusinessUnit.Parameters.AddWithValue("@created_at", DateTime.Now);
            str_BusinessUnitParam += ")";
            sco_BusinessUnit.CommandText = str_BusinessUnit + str_BusinessUnitParam;
            arl_SelectedVal.Add(sco_BusinessUnit);
        }
        return arl_SelectedVal;
    }
    #endregion
    //----------------End for Org Security------------------
    /// <summary>
    /// To validate password
    /// </summary>
    /// <param name="lbl_message">Lable for error message.</param>
    /// <returns>True / False</returns>
    // Added by 'Imran Gani' on 25-Nov-2013.
    private bool validatePassword(ref Label lbl_message)
    {
        security hdds = new security();
        string err = string.Empty; 
        try
        {
            if (Request.QueryString["PK"] != null) return true;
            if (!hdds.validatePasswordLength(TB_password.Text, ref err))
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + err, true);
                return false;
            } 
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("UserWizard: validatePassword: Error: " + ex.Message);
        }
        return true;
    }
}
